package com.yxr.affairs;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.jpeng.jptabbar.BadgeDismissListener;
import com.jpeng.jptabbar.JPTabBar;
import com.jpeng.jptabbar.OnTabSelectListener;
import com.tencent.bugly.beta.Beta;
import com.umeng.analytics.MobclickAgent;
import com.yxr.affairs.base.BaseActivity;
import com.yxr.affairs.fragment.AccountActivity1;
import com.yxr.affairs.fragment.HomeFragment;
import com.yxr.affairs.fragment.InvestFragment;
import com.yxr.affairs.fragment.StoreFragment;
import com.yxr.affairs.utils.CommonProgressDialog;
import com.yxr.affairs.utils.ToastUtil;
import com.yxr.affairs.utils.Tools;
import com.yxr.affairs.utils.UserInfo1;
import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;

public class MainActivity extends BaseActivity
        implements BadgeDismissListener, OnTabSelectListener {

    private SparseArray<String> mSparseTags = new SparseArray<>();

    private static final int POS_0 = 0;
    private static final int POS_1 = 1;
    private static final int POS_2 = 2;


    @BindView(R.id.ah_container)
    FrameLayout mAhContainer;
    @BindView(R.id.ah_tabbar)
    JPTabBar mAhTabbar;

    private HomeFragment mHF;
    private InvestFragment mIF;

    private AccountActivity1 mMF;

    private int currentItem = 0;
    private CommonProgressDialog pBar;

    public static MainActivity mMian;

    // 下载存储的文件名
    private static final String DOWNLOAD_NAME = "channelWe";
    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected void initViews() {

        mMian=this;
        int vision = Tools.getVersion(this);



       // getVersion(vision);

        mAhTabbar.setTitles("首页", "财务状况", "我的")
                .setNormalIcons(R.mipmap.home_normal, R.mipmap.invest_normal, R.mipmap.more_normal)
                .setSelectedIcons(R.mipmap.home_selected, R.mipmap.invest_selected, R.mipmap.more_selected)
                .generate();
        mAhTabbar.setTabListener(this);

        mSparseTags.put(POS_0, "Home");
        mSparseTags.put(POS_1, "Invest");
        mSparseTags.put(POS_2, "More");

        loadFragment(POS_0);

     //   EventBus.getDefault().register(this);
        push();
        getPermission();

        Beta.checkUpgrade(true, false);//这是手动检查更新，如果没有新版本发布，会提示当前是最新版本

    }
    /*private void getVersion(final int vision) {
//         {"data":{"content":"其他bug修复。","id":"2","api_key":"android",
//         // "version":"2.1"},"msg":"获取成功","status":1}
        String data = "";
        //网络请求获取当前版本号和下载链接
        //实际操作是从服务器获取
        //demo写死了

        String newversion = "2.1";//更新新的版本号
        String content = "\n" +
                "新的版本已经更新了\n" +
                "\n" + "\n" +"需要用户自己下载新的版本\n" +
                "2.侧边栏、弹框优化 —— 这个你自己去探索吧，总得留点悬念嘛-。-\n";//更新内容
        String url = "http://openbox.mobilem.360.cn/index/d/sid/3429345";//安装包下载地址

        double newversioncode = Double
                .parseDouble(newversion);
        int cc = (int) (newversioncode);

        System.out.println(newversion + "v" + vision + ",,"
                + cc);
        if (cc != vision) {
            if (vision < cc) {
                System.out.println(newversion + "v"
                        + vision);
                // 版本号不同
                ShowDialog(vision, newversion, content, url);
            }
        }
    }*/

   /* private void ShowDialog(int vision, String newversion, String content,
                            final String url) {

        new android.app.AlertDialog.Builder(this)
                .setTitle("版本更新")
                .setMessage(content)
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        pBar = new CommonProgressDialog(MainActivity.this);
                        pBar.setCanceledOnTouchOutside(false);
                        pBar.setTitle("正在下载");
                        pBar.setCustomTitle(LayoutInflater.from(
                                MainActivity.this).inflate(
                                R.layout.title_dialog, null));
                        pBar.setMessage("正在下载");
                        pBar.setIndeterminate(true);
                        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        pBar.setCancelable(true);
                        // downFile(URLData.DOWNLOAD_URL);
                        final DownloadTask downloadTask = new DownloadTask(
                                MainActivity.this);
                        downloadTask.execute(url);
                        pBar.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                downloadTask.cancel(true);
                            }
                        });
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }*/
    /*class DownloadTask extends AsyncTask<String, Integer, String> {

        private Context context;
        private PowerManager.WakeLock mWakeLock;

        public DownloadTask(Context context) {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            File file = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                // expect HTTP 200 OK, so we don't mistakenly save error
                // report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP "
                            + connection.getResponseCode() + " "
                            + connection.getResponseMessage();
                }
                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength();
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    file = new File(Environment.getExternalStorageDirectory(),
                            DOWNLOAD_NAME);

                    if (!file.exists()) {
                        // 判断父文件夹是否存在
                        if (!file.getParentFile().exists()) {
                            file.getParentFile().mkdirs();
                        }
                    }

                } else {
                    Toast.makeText(MainActivity.this, "sd卡未挂载",
                            Toast.LENGTH_LONG).show();
                }
                input = connection.getInputStream();
                output = new FileOutputStream(file);
                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);

                }
            } catch (Exception e) {
                System.out.println(e.toString());
                return e.toString();

            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }
                if (connection != null)
                    connection.disconnect();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // take CPU lock to prevent CPU from going off if the user
            // presses the power button during download
            PowerManager pm = (PowerManager) context
                    .getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    getClass().getName());
            mWakeLock.acquire();
            pBar.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
            pBar.setIndeterminate(false);
            pBar.setMax(100);
            pBar.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();
            pBar.dismiss();
            if (result != null) {

                Toast.makeText(context, "您未打开SD卡权限" + result, Toast.LENGTH_LONG).show();
            } else {
                // Toast.makeText(context, "File downloaded",
                // Toast.LENGTH_SHORT)
                // .show();
                update();
            }

        }
    }*/


  /*  private static final int REQUEST_CODE_SETTING = 300;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_SETTING: {
                Toast.makeText(this, R.string.message_setting_back, Toast.LENGTH_LONG).show();
                //设置成功，再次请求更新
                getVersion(Tools.getVersion(MainActivity.this));
                break;
            }
        }
    }


    private void update() {
        //安装应用
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), DOWNLOAD_NAME)),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }*/
    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            _exit();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        return;
    }

    private void _exit() {
        if (System.currentTimeMillis() - mExitTime > 2000) {
            ToastUtil.toast(this, "再按一次退出程序");
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    private long mExitTime = 0;

    @Override
    public void onDismiss(int position) {
        if (position == 2) {
            //TabItem徽章消失的回调
        }
    }

    @Override
    public void onTabSelect(int index) {
        if (currentItem == index)
            return;

        switch (index) {
            case POS_0:
            case POS_1:
                currentItem = index;
                loadFragment(index);
                break;

                case POS_2:
                if (UserInfo1.isLogin()){
                    currentItem = index;
                    loadFragment(index);
                }else{
                    LoginActicity1.startActivity(this);
                    mAhTabbar.setSelectTab(currentItem);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onClickMiddle(View middleBtn) {
        //用户点击中间的图标
    }



    @Override
    protected void onError_(Throwable e) {

    }

    @Override
    protected void onCancel_() {

    }

    public void userArticleList(int articleNum) {
        if (articleNum > 0) {
            mAhTabbar.showBadge(POS_2, articleNum);
        }
    }

    private void loadFragment(int pos){
        FragmentTransaction fTransaction = getSupportFragmentManager().beginTransaction();
        if (mHF != null) {
            fTransaction.hide(mHF);
        }
        if (mIF != null) {
            fTransaction.hide(mIF);
        }
        if (mMF != null) {
            fTransaction.hide(mMF);
        }

        Fragment mFragment = null;
        switch (pos){
            case POS_0:
                if (mHF == null) {
                    mHF = new HomeFragment();
                    fTransaction.add(R.id.ah_container, mHF, mSparseTags.get(POS_0));
                }
                mFragment = mHF;
                break;
            case POS_1:
                if (mIF == null) {
                    mIF = new InvestFragment();
                    fTransaction.add(R.id.ah_container, mIF, mSparseTags.get(POS_1));
                }
                mFragment = mIF;
                break;

            case POS_2:
                if (mMF == null) {
                    mMF = new AccountActivity1();
                    fTransaction.add(R.id.ah_container, mMF, mSparseTags.get(POS_2));
                }
                mFragment = mMF;
                break;
            default:
                break;
        }

        fTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fTransaction.show(mFragment);
        fTransaction.commit();
    }

    private void push(){
        try {
            Intent intent = getIntent();
            String s = intent.getStringExtra("fragname");
            if (s.equals(mSparseTags.get(POS_1))) {
                currentItem = POS_1;
                loadFragment(POS_1);
                mAhTabbar.setSelectTab(POS_1);
            } else if (s.equals(mSparseTags.get(POS_2))) {
                currentItem = POS_2;
                loadFragment(POS_2);
                mAhTabbar.setSelectTab(POS_2);
            }
        } catch (Exception e) {}
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        try {
            String s = intent.getStringExtra("fragname");
            if (s.equals(mSparseTags.get(POS_0))) {
                currentItem = POS_0;
                loadFragment(POS_0);
                mAhTabbar.setSelectTab(POS_0);
            }else if (s.equals(mSparseTags.get(POS_1))) {
                currentItem = POS_1;
                loadFragment(POS_1);
                mAhTabbar.setSelectTab(POS_1);
            } else if (s.equals(mSparseTags.get(POS_2))) {
                currentItem = POS_2;
                loadFragment(POS_2);
                mAhTabbar.setSelectTab(POS_2);
            }
        } catch (Exception e) {}

    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
